package cl.tinet.finalexam.ejb.user;

import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import cl.tinet.finalexam.dao.SystemBDDAO;
import cl.tinet.finalexam.exceptions.UserBadCredentialsException;
import cl.tinet.finalexam.exceptions.UserExistException;
import cl.tinet.finalexam.exceptions.UserNotFoundException;
import cl.tinet.finalexam.model.UserModel;
import cl.tinet.finalexam.utils.Encryptor;

/**
 * 
 * Bean de Usuario.
 *
 * @author tinet
 */
@Stateless(mappedName = "userbeanImpl", name = "userbeanImpl")
public class UserBeanImpl implements UserBeanInterface {

    /**
     * Persistencia de Base de datos.
     */
    @PersistenceContext(unitName = "MysqlDS")
    private EntityManager em;

    /**
     * DAO
     */
    SystemBDDAO dataDAO;

    @PostConstruct
    public void init() {
        dataDAO = new SystemBDDAO(em);
    }

    /**
     * {@inheritDoc}
     */
    public UserModel searchByUsername(String usernameToSearch)
            throws UserNotFoundException {

        UserModel userFound = null;
        userFound = dataDAO.searchByUsername(usernameToSearch);
        if (userFound == null) {
            throw new UserNotFoundException(usernameToSearch);
        }

        return userFound;
    }

    /**
     * {@inheritDoc}
     */
    public UserModel checkLogin(String username, String password)
            throws UserNotFoundException, UserBadCredentialsException {

        UserModel userToCheck = searchByUsername(username);

        if (userToCheck.getUsername().equals(username)
                && userToCheck.getPassword().equals(Encryptor.getMD5(password))) {
            System.out.println("Encontrado: " + userToCheck.getUsername());
        } else {
            throw new UserBadCredentialsException(userToCheck.getUsername());
        }
        return userToCheck;
    }

    /**
     * 
     * TODO doc information expected for addUser method.
     *
     * @param userToAdd
     * @throws UserExistException
     */
    public void addUser(UserModel userToAdd) throws UserExistException {

        try {
            UserModel userTemp;
            userTemp = searchByUsername(userToAdd.getUsername());
            if(userTemp != null){
                throw new UserExistException(userToAdd.getUsername());
            }
        } catch (UserNotFoundException e) {
            dataDAO.addUser(userToAdd);
        }

    }

    /**
     * {@inheritDoc}
     */
    public Collection<UserModel> allUsers() {
       
        
        return dataDAO.allUsers();
    }
    
    public UserModel searchUserByID(int userID){
        return dataDAO.searchByUserID(userID);
    }
    
    

}
